package com.tianxin.workbao.workBao.manager;

import android.app.ProgressDialog;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by hacker on 2017/8/16.
 */

public class DownLoadManager {
    public static File getFileFromServer(String path, ProgressDialog pd) {
        try {
            return getFile(path, pd);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static File getFile(String path, ProgressDialog pd) throws Exception {
        URL url = new URL(com.tianxin.workbao.workBao.common.URL.getDownloadApkUrl());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        String filepath = "filepath=" + URLEncoder.encode(path, "UTF-8");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(filepath);
        //获取到文件的大小
        pd.setMax(conn.getContentLength());
        InputStream is = conn.getInputStream();
        File file;
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            file = new File(Environment.getExternalStorageDirectory() ,"txmy.apk");
        } else {
            file = new File("txmy.apk");
        }
        FileOutputStream fos = new FileOutputStream(file);
        BufferedInputStream bis = new BufferedInputStream(is);

        byte[] buffer = new byte[1024];
        int len;
        int total = 0;
        while ((len = bis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
            total += len;
            //获取当前下载量
            pd.setProgress(total);
        }
        fos.close();
        bis.close();
        is.close();
        return file;
    }
}


